iT邦幫忙

2023 iThome 鐵人賽

DAY 12
0

Converter

  1. 建立專案,加入→現有專案,將BindingLibrary加入專案

  2. 相依性→新增專案供參考,BindingLibrary打勾

  3. 新增ViewModels資料夾,加入類別MainViewModel
    先using BindingLibrary,class前面加internal後繼承NotifyPropertyBase

using BindingLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sample.ViewModels
{
    internal class MainViewModel : NotifyPropertyBase
    {
        private float _number=0;
        public float Number
        {
            get { return _number; }
            set { SetProperty(ref _number, value); }
        }
    }
}
  1. MainWindow.xaml加入路徑xmlns:vm="clr-namespace:Sample.ViewModels”及使用MainViewModel
<Window x:Class="Sample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Sample"
        xmlns:vm="clr-namespace:Sample.ViewModels"
       mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <vm:MainViewModel/>
    </Window.DataContext>
    
    <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
        <TextBox Width="100" Text="{Binding Number, Mode=OneWayToSource ,UpdateSourceTrigger=PropertyChanged}"/>
        <TextBlock Width="100" Text="{Binding Number}"/>
    </StackPanel>
</Window>
  1. 新增Converters資料夾,加入類別ValueColorConverter,class前面加internal後繼承IValueConverter
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media;

namespace Sample.Converters
{
    internal class ValueColorConverter : IValueConverter
    {
        object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var v = (float)value;
            if (v > 100.5) return new SolidColorBrush(Colors.GreenYellow);
            else return new SolidColorBrush(Colors.Red);
        }

        object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
  1. 補轉換器
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
        <TextBox Width="100" Text="{Binding Number, Mode=OneWayToSource ,UpdateSourceTrigger=PropertyChanged}"/>
        <TextBlock Width="100" Text="{Binding Number}" Foreground="{Binding Number, Converter={StaticResource NumberColorConverter}}"/>
</StackPanel>

上一篇
斷捨離
下一篇
方法Method
系列文
自我挑戰雜記18
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言